# 塔罗牌解读系统

import random
import datetime
from datetime import datetime

class TarotDivination:
    def __init__(self):
        # 初始化塔罗牌数据
        self.tarot_cards = self._init_tarot_cards()
        self.spreads = self._init_spreads()
    
    def _init_tarot_cards(self):
        """初始化塔罗牌数据库"""
        # 大阿卡纳牌（22张）
        major_arcana = {
            0: {
                "name": "愚者",
                "chinese_name": "愚者",
                "upright": "新的开始，冒险，自发性，潜力，自由",
                "reversed": "鲁莽，冒险，愚蠢的选择，漫无目的",
                "image": "fool.jpg",
                "element": "风"
            },
            1: {
                "name": "The Magician",
                "chinese_name": "魔术师",
                "upright": "创造力，意志力，技巧，行动力，专注",
                "reversed": "操纵，计划不周，潜能未开发，技能欠缺",
                "image": "magician.jpg",
                "element": "火"
            },
            2: {
                "name": "The High Priestess",
                "chinese_name": "女祭司",
                "upright": "直觉，潜意识，神秘，内在声音，智慧",
                "reversed": "秘密，断绝联系，忽视直觉，表面信息",
                "image": "priestess.jpg",
                "element": "水"
            },
            # 其他大阿卡纳牌...
            21: {
                "name": "The World",
                "chinese_name": "世界",
                "upright": "完成，整合，成就，旅行，和谐",
                "reversed": "未完成，短视，缺乏收尾，停滞",
                "image": "world.jpg",
                "element": "土"
            }
        }
        
        # 小阿卡纳牌（56张）
        # 权杖（Wands）- 对应火元素
        wands = {}
        for i in range(1, 11):
            wands[f"wands_{i}"] = {
                "name": f"{i} of Wands",
                "chinese_name": f"权杖{i}",
                "suit": "wands",
                "element": "火",
                "upright": self._get_wands_meaning(i, True),
                "reversed": self._get_wands_meaning(i, False),
                "image": f"wands_{i}.jpg"
            }
        
        # 圣杯（Cups）- 对应水元素
        cups = {}
        for i in range(1, 11):
            cups[f"cups_{i}"] = {
                "name": f"{i} of Cups",
                "chinese_name": f"圣杯{i}",
                "suit": "cups",
                "element": "水",
                "upright": self._get_cups_meaning(i, True),
                "reversed": self._get_cups_meaning(i, False),
                "image": f"cups_{i}.jpg"
            }
        
        # 宝剑（Swords）- 对应风元素
        swords = {}
        for i in range(1, 11):
            swords[f"swords_{i}"] = {
                "name": f"{i} of Swords",
                "chinese_name": f"宝剑{i}",
                "suit": "swords",
                "element": "风",
                "upright": self._get_swords_meaning(i, True),
                "reversed": self._get_swords_meaning(i, False),
                "image": f"swords_{i}.jpg"
            }
        
        # 星币（Pentacles）- 对应土元素
        pentacles = {}
        for i in range(1, 11):
            pentacles[f"pentacles_{i}"] = {
                "name": f"{i} of Pentacles",
                "chinese_name": f"星币{i}",
                "suit": "pentacles",
                "element": "土",
                "upright": self._get_pentacles_meaning(i, True),
                "reversed": self._get_pentacles_meaning(i, False),
                "image": f"pentacles_{i}.jpg"
            }
        
        # 宫廷牌 - 侍从、骑士、王后、国王
        court_cards = {
            "wands_page": {
                "name": "Page of Wands",
                "chinese_name": "权杖侍从",
                "suit": "wands",
                "element": "火",
                "upright": "热情，探索，能量，消息",
                "reversed": "缺乏方向，拖延，不稳定",
                "image": "wands_page.jpg"
            },
            # 其他宫廷牌...
        }
        
        # 合并所有牌
        all_cards = {}
        all_cards.update(major_arcana)
        all_cards.update(wands)
        all_cards.update(cups)
        all_cards.update(swords)
        all_cards.update(pentacles)
        all_cards.update(court_cards)
        
        return all_cards
    
    def _init_spreads(self):
        """初始化塔罗牌阵"""
        spreads = {
            "three_card": {
                "name": "三张牌阵",
                "description": "简单而有效的牌阵，可以代表过去、现在和未来，或者问题、行动和结果。",
                "positions": [
                    {"name": "过去/问题", "description": "代表过去的影响或当前问题的根源"},
                    {"name": "现在/行动", "description": "代表当前情况或需要采取的行动"},
                    {"name": "未来/结果", "description": "代表可能的结果或未来发展"}
                ]
            },
            "celtic_cross": {
                "name": "凯尔特十字牌阵",
                "description": "最经典的塔罗牌阵之一，提供全面的分析。",
                "positions": [
                    {"name": "当前状况", "description": "代表咨询者目前的状况"},
                    {"name": "挑战", "description": "代表当前面临的挑战或障碍"},
                    {"name": "过去", "description": "代表过去的影响"},
                    {"name": "未来", "description": "代表即将到来的影响"},
                    {"name": "目标/恐惧", "description": "代表咨询者的目标或恐惧"},
                    {"name": "潜意识", "description": "代表潜意识的影响"},
                    {"name": "自我认知", "description": "代表咨询者如何看待自己"},
                    {"name": "外部影响", "description": "代表外部环境和他人的影响"},
                    {"name": "希望/恐惧", "description": "代表咨询者的希望或恐惧"},
                    {"name": "最终结果", "description": "代表最终可能的结果"}
                ]
            },
            "relationship": {
                "name": "关系牌阵",
                "description": "专门用于分析人际关系的牌阵。",
                "positions": [
                    {"name": "自己", "description": "代表咨询者在关系中的角色"},
                    {"name": "对方", "description": "代表关系中的另一方"},
                    {"name": "关系现状", "description": "代表关系的当前状态"},
                    {"name": "关系基础", "description": "代表关系的基础"},
                    {"name": "过去影响", "description": "代表过去对关系的影响"},
                    {"name": "未来发展", "description": "代表关系的未来发展"}
                ]
            }
        }
        return spreads
    
    def _get_wands_meaning(self, number, is_upright):
        """获取权杖牌的含义"""
        meanings = {
            1: ("开始，灵感，创造力", "虚假的开始，延迟，缺乏灵感"),
            2: ("计划，决定，发现", "恐惧做决定，拖延，不稳定"),
            3: ("扩展，成长，合作", "延迟，缺乏合作，障碍"),
            4: ("稳定，和谐，家庭", "不稳定，不和谐，缺乏支持"),
            5: ("冲突，竞争，挑战", "避免冲突，退缩，内部斗争"),
            6: ("胜利，成功，公众认可", "延迟，骄傲，过度自信"),
            7: ("毅力，挑战，竞争", "精疲力竭，放弃，被压倒"),
            8: ("速度，行动，旅行", "延迟，挫折，缺乏方向"),
            9: ("准备，防御，坚持", "顽固，偏执，缺乏准备"),
            10: ("负担，责任，压力", "压力过大，崩溃，解脱")
        }
        return meanings.get(number, ("未知", "未知"))[0 if is_upright else 1]
    
    def _get_cups_meaning(self, number, is_upright):
        """获取圣杯牌的含义"""
        meanings = {
            1: ("新的感情，直觉，创造力", "情感枯竭，创造力阻塞，孤独"),
            2: ("和谐，伙伴关系，吸引力", "失衡，分离，误解"),
            3: ("庆祝，友谊，合作", "过度放纵，疏远，孤独"),
            4: ("沉思，冥想，无聊", "行动，新机会，摆脱停滞"),
            5: ("失落，悲伤，遗憾", "接受，前进，找到希望"),
            6: ("怀旧，回忆，重聚", "停滞于过去，拒绝前进，幻想"),
            7: ("幻想，选择，欺骗", "现实，明确选择，决心"),
            8: ("放弃，转变，倦怠", "喜悦，回归，重新参与"),
            9: ("满足，情感满足，愿望实现", "物质主义，表面满足，过度放纵"),
            10: ("和谐，完美，幸福家庭", "破碎的家庭，不和谐，价值观不同")
        }
        return meanings.get(number, ("未知", "未知"))[0 if is_upright else 1]
    
    def _get_swords_meaning(self, number, is_upright):
        """获取宝剑牌的含义"""
        meanings = {
            1: ("清晰，真相，突破", "混乱，虚假，不公正"),
            2: ("僵局，决定，和平", "紧张，恐惧，不诚实"),
            3: ("心碎，悲伤，分离", "恢复，宽恕，释放"),
            4: ("休息，恢复，冥想", "倦怠，压力，缺乏进展"),
            5: ("冲突，争论，竞争", "和解，解决，释放紧张"),
            6: ("过渡，旅程，离开", "阻碍，混乱，延迟"),
            7: ("欺骗，策略，秘密计划", "揭露，诚实，放弃计划"),
            8: ("限制，困境，受害者心态", "自由，新视角，接受"),
            9: ("焦虑，恐惧，噩梦", "希望，清晰，面对恐惧"),
            10: ("结束，失败，痛苦", "恢复，希望，新开始")
        }
        return meanings.get(number, ("未知", "未知"))[0 if is_upright else 1]
    
    def _get_pentacles_meaning(self, number, is_upright):
        """获取星币牌的含义"""
        meanings = {
            1: ("机会，繁荣，新的财富", "错失机会，物质损失，贪婪"),
            2: ("平衡，适应，时间管理", "失衡，混乱，优先级错误"),
            3: ("技能，合作，商业", "缺乏团队合作，混乱，低质量工作"),
            4: ("安全，保守，控制", "风险，过度控制，错失机会"),
            5: ("贫困，孤立，担忧", "恢复，新机会，精神富足"),
            6: ("慷慨，帮助，分享", "自私，债务，不平等"),
            7: ("耐心，长期视野，投资", "缺乏耐心，短视，机会损失"),
            8: ("技能，勤奋，细节", "完美主义，工作狂，缺乏深度"),
            9: ("富足，奢侈，自给自足", "物质损失，缺乏安全感，孤立"),
            10: ("财富，家庭，传统", "家庭冲突，财务损失，破产")
        }
        return meanings.get(number, ("未知", "未知"))[0 if is_upright else 1]
    
    def draw_cards(self, spread_name, birth_date, current_time, question):
        """
        抽取塔罗牌并进行解读
        
        参数:
        spread_name: 牌阵名称
        birth_date: 用户生日，格式为"YYYY-MM-DD"
        current_time: 当前时间，格式为"YYYY-MM-DD HH:MM:SS"
        question: 用户提出的问题
        
        返回:
        塔罗牌解读结果
        """
        # 将生日和当前时间转换为数值
        birth_dt = datetime.strptime(birth_date, "%Y-%m-%d")
        current_dt = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S")
        
        # 设置随机种子，确保结果的一致性
        seed = (
            birth_dt.year + birth_dt.month + birth_dt.day +
            current_dt.year + current_dt.month + current_dt.day +
            current_dt.hour + current_dt.minute + current_dt.second +
            len(question)
        )
        random.seed(seed)
        
        # 获取牌阵信息
        spread = self.spreads.get(spread_name, self.spreads["three_card"])
        positions = spread["positions"]
        
        # 创建牌组（复制所有牌的键）
        deck = list(self.tarot_cards.keys())
        random.shuffle(deck)
        
        # 抽取牌
        drawn_cards = []
        for i in range(len(positions)):
            # 抽一张牌
            card_key = deck.pop(0)
            card = self.tarot_cards[card_key].copy()
            
            # 随机决定正位或逆位
            is_upright = random.choice([True, False])
            card["position"] = is_upright
            card["position_name"] = "正位" if is_upright else "逆位"
            card["meaning"] = card["upright"] if is_upright else card["reversed"]
            
            # 添加位置信息
            card["spread_position"] = positions[i]["name"]
            card["position_description"] = positions[i]["description"]
            
            drawn_cards.append(card)
        
        # 生成整体解读
        overall_interpretation = self._generate_overall_interpretation(drawn_cards, question)
        
        # 返回结果
        result = {
            "spread": {
                "name": spread["name"],
                "description": spread["description"]
            },
            "question": question,
            "cards": drawn_cards,
            "overall_interpretation": overall_interpretation,
            "divination_time": current_time,
            "user_info": {
                "birth_date": birth_date
            }
        }
        
        return result
    
    def _generate_overall_interpretation(self, cards, question):
        """生成整体解读"""
        # 分析牌面元素分布
        elements = {"火": 0, "水": 0, "风": 0, "土": 0}
        major_arcana_count = 0
        suits = {"wands": 0, "cups": 0, "swords": 0, "pentacles": 0}
        
        for card in cards:
            if "element" in card:
                elements[card["element"]] += 1
            
            if isinstance(card.get("name", ""), int) or card.get("name", "").isdigit():
                major_arcana_count += 1
            
            if "suit" in card:
                suits[card["suit"]] += 1
        
        # 确定主导元素
        dominant_element = max(elements, key=elements.get)
        
        # 根据问题类型和牌面分布生成解读
        interpretation = ""
        
        # 根据问题关键词确定问题类型
        question_lower = question.lower()
        if any(word in question_lower for word in ["爱情", "感情", "关系", "婚姻"]):
            if elements["水"] > elements["火"]:
                interpretation += "在感情方面，您目前处于一个情感丰富但可能缺乏激情的阶段。"
            else:
                interpretation += "您的感情生活充满激情，但可能需要更多的情感交流和理解。"
            
            if suits["cups"] > suits["wands"]:
                interpretation += "牌面显示您的情感世界丰富多彩，但可能需要更多的行动来表达。"
            else:
                interpretation += "您在感情中表现积极主动，但可能需要更多地关注伴侣的情感需求。"
        
        elif any(word in question_lower for word in ["事业", "工作", "职业", "学业"]):
            if elements["火"] > elements["土"]:
                interpretation += "在事业方面，您充满热情和创造力，但可能需要更加踏实和耐心。"
            else:
                interpretation += "您在工作中表现稳重踏实，但可能需要更多的创新和冒险精神。"
            
            if suits["pentacles"] > suits["wands"]:
                interpretation += "牌面显示您注重物质成就和稳定性，这将为您带来长期的职业发展。"
            else:
                interpretation += "您的职业发展充满活力和机遇，但需要更加关注长期规划和稳定性。"
        
        elif any(word in question_lower for word in ["财富", "金钱", "财运", "投资"]):
            if elements["土"] > elements["风"]:
                interpretation += "在财富方面，您注重稳健和积累，这将为您带来长期的财务安全。"
            else:
                interpretation += "您的财务状况可能面临变化和挑战，需要更加谨慎和务实的态度。"
            
            if suits["pentacles"] > 1:
                interpretation += "牌面显示您有良好的财务管理能力，继续保持将带来丰厚回报。"
            else:
                interpretation += "您可能需要更加关注财务规划和管理，避免不必要的风险和损失。"
        
        else:
            # 通用解读
            interpretation += f"牌面整体呈现{dominant_element}元素主导，表示"
            if dominant_element == "火":
                interpretation += "您当前充满热情、创造力和行动力。"
            elif dominant_element == "水":
                interpretation += "您当前情感丰富，直觉敏锐，人际关系和谐。"
            elif dominant_element == "风":
                interpretation += "您当前思维活跃，沟通顺畅，但可能面临决策挑战。"
            elif dominant_element == "土":
                interpretation += "您当前注重实际和稳定，物质基础良好，但可能缺乏变化。"
        
        # 根据大阿卡纳牌的数量添加解读
        if major_arcana_count > len(cards) / 2:
            interpretation += "\n\n牌面中大阿卡纳牌占比较高，表明您正处于人生的重要转折点，外部力量和命运的影响较大。这段时期的经历和决定可能对您的未来产生深远影响。"
        
        # 添加建议
        interpretation += "\n\n根据牌面，建议您："
        
        if elements["火"] > elements["水"]:
            interpretation += "\n- 保持热情的同时，多关注自己和他人的情感需求"
        else:
            interpretation += "\n- 在情感丰富的同时，适当增加行动力和决断力"
        
        if elements["土"] > elements["风"]:
            interpretation += "\n- 在稳健踏实的基础上，增加一些创新思维和灵活性"
        else:
            interpretation += "\n- 在思维活跃的同时，注重实际行动和落地执行"
        
        # 根据牌面特点添加具体建议
        special_cards = [card for card in cards if card.get("name") in ["The Tower", "Death", "The Devil", "The Star", "The Sun"]]
        if special_cards:
            interpretation += "\n\n特别提示："
            for card in special_cards:
                if card["name"] == "The Tower":
                    interpretation += f"\n- {card['chinese_name']}牌提示您可能面临突然的变化或挑战，保持冷静和适应力至关重要"
                elif card["name"] == "Death":
                    interpretation += f"\n- {card['chinese_name']}牌象征转变和重生，而非负面结局，拥抱变化将带来新的机遇"
                elif card["name"] == "The Devil":
                    interpretation += f"\n- {card['chinese_name']}牌提醒您注意可能的束缚或不健康的依恋，寻求自由和平衡"
                elif card["name"] == "The Star":
                    interpretation += f"\n- {card['chinese_name']}牌带来希望和灵感，相信自己的直觉和内在指引"
                elif card["name"] == "The Sun":
                    interpretation += f"\n- {card['chinese_name']}牌预示成功和喜悦，保持乐观积极的态度将带来更多好运"
        
        return interpretation

# 使用示例
if __name__ == "__main__":
    tarot = TarotDivination()
    result = tarot.draw_cards(
        spread_name="three_card",
        birth_date="1990-01-15",
        current_time="2025-05-28 10:30:00",
        question="我的事业发展如何？"
    )
    print(result)
